package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"time"

	"github.com/robfig/cron/v3"
)

// 机器人 Webhook 地址
const webhookURL = "https://open.feishu.cn/open-apis/bot/v2/hook/d8100ad1-a2bc-4461-afcb-4d3a73369927"

func main() {
	c := cron.New(cron.WithSeconds())

	// _, err := c.AddFunc("0 * * * * *", func() {
	_, err := c.AddFunc("*/10 * * * * *", func() {
		fmt.Println("每分钟触发任务，当前时间戳: ", time.Now().Unix())
		formattedTime := time.Now().Format("2006/01/02 15:04:05")
		sendLarkBotMessage("无论在干什么，请记得及时喝水\n当前时间: " + formattedTime)

	})
	if err != nil {
		fmt.Println("添加定时任务失败: ", err)
		return
	}
	c.Start()
	fmt.Println("飞书定时消息机器人启动成功...")
	select {} // 阻塞主线程
}

func sendLarkBotMessage(content string) {

	// at所有人
	// messageWithAt := "<at user_id=\"all\">所有人</at>\n" + content

	// at指定人
	// messageWithAt := "<at user_id=\"user_id_1\">易义豪</at>\n" +content

	// at多个用户
	messageWithAt := "<at user_id=\"user_id_1\">易义豪</at> <at user_id=\"all\">所有人</at>\n" + content

	message := map[string]interface{}{
		"msg_type": "text",
		"content": map[string]string{
			"text": messageWithAt,
		},
	}

	jsonData, err := json.Marshal(message)
	if err != nil {
		fmt.Println("消息序列化失败: ", err)
		return
	}

	resp, err := http.Post(webhookURL, "application/json", bytes.NewBuffer(jsonData))
	if err != nil {
		fmt.Println("发送请求失败：", err)
		return
	}
	defer func(Body io.ReadCloser) {
		err := Body.Close()
		if err != nil {
			fmt.Println("关闭响应体失败:", err)
		}
	}(resp.Body)

	body, _ := io.ReadAll(resp.Body)

	fmt.Printf("飞书响应状态码：%d,响应体: %s\n", resp.StatusCode, string(body))

}
